#!/bin/bash

# 读取 .env.compose 文件
source .env.compose

# 检查是否使用本地服务
USE_LOCAL_DB=${USE_LOCAL_DB:-false}
USE_LOCAL_REDIS=${USE_LOCAL_REDIS:-false}

echo "=== 启动配置 ==="
echo "使用本地数据库: $USE_LOCAL_DB"
echo "使用本地Redis: $USE_LOCAL_REDIS"
echo "================="

# 停止现有服务
echo "停止现有服务..."
docker-compose down

# 根据配置启动服务
if [ "$USE_LOCAL_DB" = "true" ] || [ "$USE_LOCAL_REDIS" = "true" ]; then
    echo "启动本地服务..."
    # 使用 override 文件启动本地服务
    docker-compose -f docker-compose.yml -f docker-compose.override.yml up -d
else
    echo "仅启动应用服务（使用远程数据库和Redis）..."
    # 修改主配置文件，移除依赖
    # 创建临时配置文件
    cat > docker-compose.remote.yml << EOF
name: class-schedule

services:
  class-schedule-service:
    build:
      context: .
      dockerfile: backend/Dockerfile
    container_name: class-schedule-service
    env_file:
      - .env.compose
    environment:
      POSTGRES_HOST: \${POSTGRES_HOST}
      POSTGRES_PORT: \${POSTGRES_PORT}
      REDIS_HOST: \${REDIS_HOST}
      REDIS_PORT: \${REDIS_PORT}
    ports:
      - "8001:8000"
    healthcheck:
      test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8000/docs >/dev/null || exit 1"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 20s
    restart: unless-stopped
    networks:
      - backend

  course-schedule-ui:
    build:
      context: .
      dockerfile: frontend/Dockerfile
    container_name: course-schedule-ui
    restart: unless-stopped
    environment:
      - NODE_ENV=production
      - NEXT_PUBLIC_API_BASE_URL=http://class-schedule-service:8001/api
      - NEXT_PUBLIC_API_TIMEOUT=30000
      - PORT=3000
    networks:
      - backend
      - nginx_general_bridge

networks:
  backend:
    driver: bridge
  nginx_general_bridge:
    external: true
EOF
    
    docker-compose -f docker-compose.remote.yml up -d
    rm docker-compose.remote.yml
fi

echo "服务启动完成！"
echo "查看服务状态: docker-compose ps"
echo "查看日志: docker-compose logs -f"
